from django.contrib import admin

from app.forms import ArticleAdminModelForm
from app.models import Category, Tag, Article, Comment, Option


# list_display 设置要显示在列表中的字段
# list_per_page 设置每页显示多少条记录，默认是100条
# ordering 设置默认排序字段，负号开头表示降序排序
# list_display_links 设置列表可以进去编辑页面的字段
# list_editable 设置默认可编辑字段
# readonly_fields 设置只读字段
# fk_fields 设置显示外键字段
# list_filter 过滤器
# search_fields 搜索字段


class CategoryAdmin(admin.ModelAdmin):
    list_display = ('id', 'name', 'article_count')
    list_per_page = 50
    ordering = ('id',)
    list_display_links = ('id', 'name',)
    readonly_fields = ('id',)
    list_filter = ('id',)
    search_fields = ('name',)

    def article_count(self, obj):
        return Article.objects.filter(category=obj.id).count()

    article_count.short_description = '文章数'


class TagAdmin(admin.ModelAdmin):
    list_display = ('id', 'name', 'article_count')
    list_display_links = ('id', 'name',)
    readonly_fields = ('id',)

    def article_count(self, obj):
        return Article.objects.filter(tags=obj.id).count()

    article_count.short_description = '文章数'


class ArticleAdmin(admin.ModelAdmin):
    form = ArticleAdminModelForm

    list_display = ('id', 'title', 'category', 'views')
    list_display_links = ('id', 'title',)
    readonly_fields = ('id', 'views')
    ordering = ('-updated_at',)
    filter_vertical = ('tags',)


class CommentAdmin(admin.ModelAdmin):
    list_display = ('id', 'ip', 'article', 'a_parent_id', 'created_at')
    search_fields = ('ip', 'content')

    def a_parent_id(self, obj):
        if obj.parent:
            return obj.parent.id
        else:
            return "-"

    a_parent_id.short_description = '上级Id'


class OptionAdmin(admin.ModelAdmin):
    pass


admin.site.register(Category, CategoryAdmin)
admin.site.register(Tag, TagAdmin)
admin.site.register(Article, ArticleAdmin)
admin.site.register(Comment, CommentAdmin)
admin.site.register(Option, OptionAdmin)
